'use strict'
class design{
    constructor (){

    }
    __mid () { //启用token-verify中间件
        return [
            {
                name:'token-verify',
                path:['list','post','delete']
            }
        ]
    }
    async list (c){ //请求设计列表
        let userId = c.box.user.userId;
        let sqltext = `SELECT * FROM design WHERE "userId"=$1`;
        let r = await c.service.psql.query(sqltext,[userId]);
        c.send(JSON.stringify(r.rows))
    }
    async get(c){ //请求某一设计
        let filePath = `/home/images/${c.param.id}`;
        await c.helper.pipe(filePath,c.reply)
    }
    async post(c) { //提交设计(传递的数据是图片,返回前端提交成功提示信息)   
        let userId = c.box.user.userId;
        let f = c.getFile('img');
        
        if (!f) {
            return c.status(400).send('image not found')
        }

        // 根据传入的原始文件名生成唯一文件名，主要使用f.filename的扩展名 
        let fname = c.helper.makeName(f.filename);

        // 移动文件到指定位置
        let filePath = `${c.service.imagePath}/${fname}`;
        await c.moveFile(f,filePath);//如果没有images目录的话会导致报错，app.js中会检测并创建images目录

        try {
            let sqltext = `INSERT INTO `
                            +`design("userId","designContent")`
                            +`VALUES ($1,$2)`;
            let r = await c.service.psql.query(sqltext,[userId,filePath]);
            if (r.rowCount != 0) { //对是否提交设计成功做判断
                c.send('Post design success!')
            } else {
                c.status(500).send('Post design failed!')
            }
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
    }
    async delete(c) {
        const fs = require('fs');
        let userId = c.box.user.userId;
        let designId = c.param.id;
        try {
            let sql = `SELECT * FROM design WHERE "designId"=$1`;
            let ret = await c.service.psql.query(sql,[designId]);
            let picName = ret.rows[0].designContent;
            console.log("picName",picName);
            fs.unlinkSync(picName);
            let sqltext = `DELETE FROM design WHERE "designId"=$1`;
            let r = await c.service.psql.query(sqltext,[designId]);
            
            if (r.rowCount != 0) { //对是否查询到并删除成功做判断
                c.send('Delete design success!')
            } else {
                c.status(500).send('Delete design failed!')
            }
            
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
    }
}
module.exports = design;